﻿using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace STX.Service.Valid.BizUserValid
{
    public class Add : ValidExpression<STX.Domain.BizUser>
    {
        public override void ValidEntity(ValidationResult result, Domain.BizUser entity)
        {
            if (!CommonlyUsedRegex.IsEmail(entity.Email))
            {
                PushError(result, "邮件地址格式不正确");
            }
            NoEmpty(result, "邮件", entity.Email);
            NoEmpty(result, "密码", entity.Password);
            NoEmpty(result, "昵称", entity.Username);
            var bizUserRepository = Transaction.GetRepository<Domain.BizUser>();
            var modelByEmail = bizUserRepository.FindAll().FirstOrDefault(o => o.Email.Trim() == entity.Email.Trim());
            if (modelByEmail != null)
            {
                PushError(result, "此邮件地址已经被占用了");
            }
            var modelByUsername = bizUserRepository.FindAll().FirstOrDefault(o => o.Username.Trim() == entity.Username.Trim());
            if (modelByUsername != null)
            {
                PushError(result, "此用户名已经被占用了");
            }
            
            if (entity.Password != null && entity.Password.Length <= 6)
            {
                PushError(result, "密码不能小于6位");
            }
        }
    }
}
